export const setLocalStorage = ({ key, value }) => {
  return wx.setStorage({ key, data: JSON.stringify(value) })
}
export const getLocalStorage = async (key) => {
  try {
    const res = await wx.getStorage({ key })
    if (res && res.data) {
      return JSON.parse(res.data)
    }
    return null
  } catch {
    return null 
  }
}
export const toLogOnPage = (pageThis) => {
  wx.navigateTo({
    url: '/pages/logOn/index',
    events: {
      acceptDataFromOpenedPage: function(data) {
      }
    },
    success: function(res) {
    }
  })
}
export const validateTel = tel => /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(tel)

export const replaceItemInPlace = (data, item, formatter) => {
  for (let i = 0; i < data.length; ++i) {
    if (data[i].id === item.id) {
      if (formatter) {
        data[i] = formatter({ ...data[i], ...item })
      } else {
        data[i] = { ...data[i], ...item }
      }
      break
    }
  }
}

export const deleteItemInPlace = (data, item) => {
  for (let i = 0; i < data.length; ++i) {
    if (data[i].id === item.id) {
      data.splice(i, 1)
      break
    }
  }
}